/*
 * @Author: your name
 * @Date: 2021-05-28 15:09:30
 * @LastEditTime: 2021-05-28 16:19:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_music_api\controller\swiperlist.js
 */
const { default: axios } = require('axios')
const Router = require('koa-router')
const router = new Router()
const callCloudDB = require('../utils/callCloudDB')
const callCloudStorage = require('../utils/callCloudStorage')

// 获取列表
router.get('/list', async(ctx, next) => {
    // 默认10条数据
    const query = `db.collection('swiper').get()`
    const res = await callCloudDB(ctx, 'databasequery', query)
    // 文件下载链接
    let fileList = []
    const data = res.data.data
    for(let i = 0; i < data.length; i++) {
        fileList.push({
            fileid: JSON.parse(data[i]).fileid,
            max_age: 7200
        })
    }
    const dlRes = await callCloudStorage.download(ctx, fileList)
    const dlResArr = dlRes.data.file_list
    let returnData = []
    for (let i = 0; i < dlResArr.length;i++) {
        returnData.push({
            download_url: dlResArr[i].download_url,
            fileid: dlResArr[i].fileid,
            _id: JSON.parse(data[i])._id
        })
    }
    ctx.body = {
        code: 20000,
        data: returnData
    }
})
// 上传图片
router.post('/upload', async(ctx, next) => {
  const fileid = await callCloudStorage.upload(ctx)
  // 写入数据库
  const query = `
    db.collection('swiper').add({
      data: {
        fileid: '${fileid}'
      }
    })
  `
  const res = await callCloudDB(ctx, 'databaseadd', query)
  ctx.body = {
    code: 20000,
    id_list: res.data.id_list
  }
})
// 删除图片
router.post('/del', async(ctx, next) => {
  const { body } = ctx.request
  // 删除云数据库中的内容
  const query = `db.collection('swiper').doc('${body._id}').remove()`
  const delDBRes = await callCloudDB(ctx, 'databasedelete', query)
  // 删除云存储中的文件
  const delStorageRes = await callCloudStorage.delete(ctx, [body.fileid])
  ctx.body = {
    code: 20000,
    data: {
      delDBRes: delDBRes.data,
      delStorageRes: delStorageRes.delete_list
    }
  }
})

module.exports = router
